package org.ssssssss.magicapi;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.ssssssss.magicapi.core.config.MagicAPIProperties;
import org.ssssssss.magicapi.core.config.MagicPluginConfiguration;
import org.ssssssss.magicapi.core.model.Plugin;
import org.ssssssss.magicapi.core.service.MagicAPIService;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.watch.SimpleWatcher;
import cn.hutool.core.io.watch.WatchMonitor;
import cn.hutool.core.io.watch.Watcher;
import cn.hutool.core.io.watch.watchers.DelayWatcher;

@Configuration
public class MagicFileWatchConfiguration implements MagicPluginConfiguration {

	private final MagicAPIProperties properties;

	@Autowired
	private MagicAPIService service;
	

	@Value("${magic-api.filewatch.init-start:false}")
	public boolean initStart;
	@Value("${magic-api.filewatch.dir}")
	public String dir;
	@Value("${magic-api.filewatch.deep:1}")
	public int deep;
	@Value("${magic-api.filewatch.delay:500}")
	public int delay;
	
	@Value("${magic-api.filewatch.createApi}")
	public String createApi;
	@Value("${magic-api.filewatch.modifyApi}")
	public String modifyApi;
	@Value("${magic-api.filewatch.deleteApi}")
	public String deleteApi;
	@Value("${magic-api.filewatch.overflowApi}")
	public String overflowApi;
	
	public MagicFileWatchConfiguration(MagicAPIProperties properties) {
		this.properties = properties;
	}


	@Override
	public Plugin plugin() {
		System.out.println("文件监视插件:initStart="+initStart);
		if(service!=null) {			
			try {
				if(initStart) {
					File file2 = FileUtil.file(dir);
					//这里只监听文件或目录的修改事件(可以根据要求修改)
					WatchMonitor watchMonitor = WatchMonitor.create(file2, WatchMonitor.EVENTS_ALL);
					//watchMonitor.setWatcher(new Watcher(){
					watchMonitor.setWatcher(new DelayWatcher(new SimpleWatcher() {
						@Override
						public void onCreate(WatchEvent<?> event, Path currentPath) {
							invoteApi(event.context(),currentPath,createApi);
						}

						@Override
						public void onModify(WatchEvent<?> event, Path currentPath) {
							invoteApi(event.context(),currentPath,modifyApi);
							//Console.log("修改：{}-> {}", currentPath, obj);
						}

						@Override
						public void onDelete(WatchEvent<?> event, Path currentPath) {
							invoteApi(event.context(),currentPath,deleteApi);
							//Console.log("删除：{}-> {}", currentPath, obj);
						}

						@Override
						public void onOverflow(WatchEvent<?> event, Path currentPath) {
							invoteApi(event.context(),currentPath,overflowApi);
							//Console.log("Overflow：{}-> {}", currentPath, obj);
						}
						// 调用magic接口
						public void invoteApi(Object obj,Path currentPath, String api) {
					    	Map<String,Object> params = new HashMap<>();
					        params.put("obj",obj);
					        params.put("path",currentPath);
					        service.execute("POST",api, params);  							
						}
					},delay));

					//设置监听目录的最大深入，目录层级大于制定层级的变更将不被监听，默认只监听当前层级目录
					watchMonitor.setMaxDepth(deep);
					//启动监听
					watchMonitor.start();
				}
				//
			} catch (Exception e) {
				System.out.println("文件监视: ERROR=="+e.getMessage());
				e.printStackTrace();
			}
		}
		else {
			System.out.println("文件监视:@Autowired MagicAPIService ERROR");
		}
		return new Plugin("文件监视:mqtt+websocket+socket");
	}
}
